//
//  NetManager.m
//  03-29-apiDemo-practice
//
//  Created by student on 16/3/29.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "NetManager1.h"

@implementation NetManager1
+(void)requestInfoByCityName:(NSString *)cityname
                successBlock:(void(^)(NSString *))successBlock
                 failedBlock:(void(^)(NSError *))failBlock
{
    
    NSString *httpUrl = @"http://apis.baidu.com/apistore/weatherservice/cityname";
    NSString *curString=[cityname stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *httpArg = [NSString stringWithFormat:@"cityname=%@",curString];
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl,httpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"a47710812a161be75ac6713a123dcbde" forHTTPHeaderField: @"apikey"];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                               if (connectionError==nil) {
                                   NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                   
                                   NSDictionary *dict1=dict[@"retData"];
                                   
                                   NSString *result=[NSString stringWithFormat:@"城市:%@ 城市编码:%@ 海拔:%@ 天气情况:%@ 气温:%@~%@ 风力:%@",dict1[@"city"],dict1[@"citycode"],dict1[@"altitude"],dict1[@"weather"],dict1[@"l_tmp"],dict1[@"h_tmp"],dict1[@"WS"]];
                                   successBlock(result);
                                   
                               }
                               else
                               {
                                   failBlock(connectionError);
                               }
                           }];
    
    
}
@end
